<template>
  <div>
    <h2>计算属性简单实例</h2>
    <div>fullName:{{ fullName }}</div>
    <div>结果：{{ result }}</div>
    <hr />
    <h4>计算属性和方法的区别</h4>
    <p>计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。</p>
    <p>方法没有缓存，每当触发重新渲染时，调用方法将总会再次执行函数。</p>
    <div>方法获取的fullName:{{ getFullName() }}</div>
    <hr />
    <h4>computed的setter和getter方法</h4>
    <p>计算属性默认只有 getter ，不过在需要时你也可以提供一个 setter ：</p>
    <p>computedValue:{{ computedValue }}</p>
    <div>value:<input type="text" v-model="value" /></div>
    <button @click="setNumber">设置computedValue</button>
  </div>
</template>

<!-- <script>
export default {
  name: 'jssx',
  data() {
    return {
      firstName: 'Foo',
      lastName: 'Bar',
      score: 80,
      value: 10
    }
  },
  methods: {
    getFullName() {
      return this.firstName + ' ' + this.lastName
    },
    setNumber() {
      this.computedValue = 30
      console.log('this.computedValue: ', this.computedValue)
    }
  },
  computed: {
    fullName() {
      return this.firstName + ' ' + this.lastName
    },
    result() {
      return this.score >= 60 ? '及格' : '不及格'
    },
    computedValue: {
      // getter
      get() {
        return this.value * 2
      },
      // setter
      set(newValue) {
        this.value = newValue / 2
      }
    }
  }
}
</script> -->
<script setup>
defineOptions({
  name: 'jssx'
})
import { ref } from 'vue'
import { computed } from 'vue'
const firstName = ref('Foo')
const lastName = ref('Bar')
const score = ref(80)
const value = ref(10)
const getFullName = () => {
  return firstName.value + ' ' + lastName.value
}
const setNumber = () => {
  computedValue.value = 30
}
const fullName = computed(() => {
  return firstName.value + ' ' + lastName.value
})
const result = computed(() => {
  return score.value >= 60 ? '及格' : '不及格'
})
const computedValue = computed({
  get() {
    return value.value * 2
  },
  set(newValue) {
    value.value = newValue / 2
  }
})
</script>

<style lang="scss" scoped></style>
